<template>
    <div :class="{ 'page-2': true, setLabel: setLabel }">
        <PageTitle></PageTitle>

        <WizardSteps :active="2" />

        <div class="page-2-container">
            <!-- Time Zone -->
            <div class="section-title">{{ $t('system.ntpSystemTime.timeZoneTitle') }}</div>
            <el-divider />
            <el-form ref="apnRef" :label-width="setLabelWidth" :label-position="labelPosition" v-if="setTimeZone">
                <el-form-item :label="$t('system.ntpSystemTime.timeZone') + ':'" required>
                    <el-select id="timeZoneSelect" v-model="dataForm.timeZoneValue" :popper-append-to-body="false">
                        <div id="timeZoneOptions">
                            <el-option v-for="(item, index) in timeZoneOptions" :key="index" :value="item.value" :label="item.id"></el-option>
                        </div>
                    </el-select>
                </el-form-item>
            </el-form>

            <!-- WiFi Settings -->
            <div class="section-title">{{ $t('netWork.wifiSettings.wifiSettingsTitle') }}</div>
            <el-divider />

            <section class="section-2">
                <!-- 2.4GHz Settings -->
                <template v-if="!dataForm.to5G">
                    <div class="section-title">{{ $t('wizard.2_4Gsettings') }}</div>
                    <el-divider />
                </template>

                <el-form :model="dataForm" :rules="rules" ref="ruleForm2_4" :label-width="setLabelWidth" :label-position="labelPosition">
                    <template v-if="setWifiNameTips">
                        <el-alert show-icon :closable="false" class="wifi-name-tips" v-if="dataForm.to5G" :title="$t('wizard.version2.wifiNameTips')" type="info"> </el-alert>
                    </template>

                    <!-- WiFi Name(SSID) -->
                    <el-form-item :label="$t('netWork.wifiSettings.ssidTextMobile') + ':'" prop="wifiName2_4">
                        <el-input :maxlength="wifiNameLength" v-model="dataForm.wifiName2_4" clearable>
                            <span slot="suffix" style="color: #c6c8ce; line-height: 52px"> {{ wifiNameBytes }} / 32 </span>
                        </el-input>
                    </el-form-item>

                    <!-- WiFi Password -->
                    <el-form-item :label="$t('netWork.wifiSettings.wifiPasswordTextMobile') + ':'" prop="wifiPwd2_4">
                        <el-input :type="isHideWifiPwd2_4 ? 'password' : ''" v-model="dataForm.wifiPwd2_4" maxlength="64">
                            <template slot="suffix">
                                <div :class="isHideWifiPwd2_4 ? 'el-icon-my-eye-hide' : 'el-icon-my-eye-reveal'" @click="isHideWifiPwd2_4 = !isHideWifiPwd2_4"></div>
                            </template>
                        </el-input>
                    </el-form-item>
                </el-form>

                <!-- 5GHz Settings -->
                <template v-if="!dataForm.to5G">
                    <div class="section-title">{{ $t('wizard.5Gsettings') }}</div>
                    <el-divider />

                    <el-form :model="dataForm" :rules="rules" ref="ruleForm5" :label-width="setLabelWidth" :label-position="labelPosition">
                        <!-- WiFi Name(SSID) -->
                        <el-form-item :label="$t('netWork.wifiSettings.ssidTextMobile') + ':'" prop="wifiName5">
                            <el-input :maxlength="wifiNameLength_5G" v-model="dataForm.wifiName5" clearable>
                                <span slot="suffix" style="color: #c6c8ce; line-height: 52px"> {{ wifiNameBytes_5G }} / 32 </span>
                            </el-input>
                        </el-form-item>

                        <!-- WiFi Password -->
                        <el-form-item :label="$t('netWork.wifiSettings.wifiPasswordTextMobile') + ':'" prop="wifiPwd5">
                            <el-input :type="isHideWifiPwd5 ? 'password' : ''" v-model="dataForm.wifiPwd5" maxlength="64">
                                <template slot="suffix">
                                    <div :class="isHideWifiPwd5 ? 'el-icon-my-eye-hide' : 'el-icon-my-eye-reveal'" @click="isHideWifiPwd5 = !isHideWifiPwd5"></div>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-form>
                </template>

                <div class="check-box" >
                    <el-checkbox class="conditions-box" v-model="dataForm.to5G">{{ $t('wizard.to5G') }}</el-checkbox>
                </div>
            </section>

            <section class="btn-content">
                <el-button type="primary" @click="nextClick">{{ $t('common.nextButton') }}</el-button>
            </section>

            <section class="skip-content" v-if="showSkip">
                <el-link type="primary" @click="openSkipDialog" :underline="false">{{ $t('wizard.version2.skip') }}</el-link>
            </section>
        </div>

        <confirmDialog ref="skipRef" @confirm="skipClick">
            <span>{{ $t('wizard.version2.skipConfirm') }}</span>
        </confirmDialog>
    </div>
</template>

<script>
import { isHexString } from '@/utils/string';
import watchWindow from '@/hooks/watchWindow';
import { COMMON_TZ_OPTIONS } from '@/constant/timeZone.js';
import { getByteLength } from '@/utils/common';
import { WIZARD_ROUTE, setWizardHistory } from './wizard.data';
import { errorCode,LOCAL_KEY } from '@/constant/dict';

import PageTitle from './PageTitle.vue';
import WizardSteps from './WizardSteps.vue';
import { getNtpTime, getTimeZone } from '@/api/time';
import { getWirelessDefault } from '@/api/wireless';
import { getSystemTime } from '@/api/system';

// 是否需要强制输入登录密码
const isValidatePassword = true;

export default {
    name: 'BasicSettings',
    extends: watchWindow,
    components: {
        PageTitle,
        WizardSteps
    },
    data() {
        // WIFI 名称校验
        const nameValidator = (rule, value, callback) => {
            if (!value) {
                callback(new Error(this.$t('errorTips.cannotBeEmpty')));
            } else if (getByteLength(value) > 32) {
                //输入长度超标的提示
                callback(new Error(this.$t('errorTips.maxLength')));
            } else {
                callback();
            }
        };

        // WIFI密码校验
        const passwordValidator = (rule, value, callback) => {
            const result = this.$checkStr(value, false, false, true, false, 64, 32, 126, 8);
            if (!value) {
                callback(new Error(this.$t('errorTips.cannotBeEmpty')));
            } else if (result == errorCode.BYTEERR) {
                callback(new Error(this.$t('netWork.wifiSettings.msg_wifi_5')));
            } else if (result == errorCode.STRERR || result == errorCode.ACCIIERR) {
                callback(new Error(this.$t('netWork.wanSettings.illegalDataTitle')));
            } else if (!isHexString(value) && value.length > 63) {
                // 判断当前输入的密码是否包含非16进制字符， true-不包含，最大长度为 64，false - 最大长度为 63
                callback(new Error(this.$t('netWork.wifiSettings.msg_wifi_5')));
            } else {
                callback();
            }
        };

        // 登录密码校验
        const loginPwdValidator = (rule, value, callback) => {
            const result = this.$checkStr(value, false, false, true, false, 64, 32, 126, 8);
            if (!value && isValidatePassword) {
                callback(new Error(this.$t('errorTips.cannotBeEmpty')));
            } else if (result == errorCode.BYTEERR) {
                callback(new Error(this.$t('devicemanagement.passwordCheck1')));
            } else if (result == errorCode.STRERR || result == errorCode.ACCIIERR) {
                callback(new Error(this.$t('netWork.wanSettings.illegalDataTitle')));
            } else if (!isHexString(value) && value.length > 63) {
                // 判断当前输入的密码是否包含非16进制字符， true-不包含，最大长度为 64，false - 最大长度为 63
                callback(new Error(this.$t('devicemanagement.passwordCheck1')));
            } else {
                callback();
            }
        };
        return {
            dataForm: {
                wifiName2_4: '',
                wifiPwd2_4: '',
                wifiName5: '',
                wifiPwd5: '',
                to5G: true,
                timeZoneValue: '',
            },
            rules: {
                wifiName2_4: [
                    { required: true, message: this.$t('errorTips.cannotBeEmpty'), trigger: 'blur' },
                    { validator: nameValidator, trigger: 'blur' }
                ],
                wifiPwd2_4: [
                    { required: true, message: this.$t('errorTips.cannotBeEmpty'), trigger: 'blur' },
                    { validator: passwordValidator, trigger: 'blur' }
                ],
                wifiName5: [
                    { required: true, message: this.$t('errorTips.cannotBeEmpty'), trigger: 'blur' },
                    { validator: nameValidator, trigger: 'blur' }
                ],
                wifiPwd5: [
                    { required: true, message: this.$t('errorTips.cannotBeEmpty'), trigger: 'blur' },
                    { validator: passwordValidator, trigger: 'blur' }
                ]
            },
            isHideWifiPwd2_4: true,
            isHideWifiPwd5: true,
            timeZoneOptions: COMMON_TZ_OPTIONS,
            labelPosition: 'top',
            wifiNameBytes: 0,
            wifiNameLength: 32,
            wifiNameBytes_5G: 0,
            wifiNameLength_5G: 32,
            showSkip: false,
            wiFiBakData: {
                wifiName2_4: '',
                wifiPwd2_4: '',
                wifiName5: '',
                wifiPwd5: ''
            }
        };
    },
    methods: {
        // 获取WiFi数据
        async fetchWiFiData() {
            const {ssid_24g,ssid_5g,key_24g,key_5g} = await getWirelessDefault();
            this.dataForm.wifiName2_4 = ssid_24g;
            this.dataForm.wifiPwd2_4 = key_24g;
            this.dataForm.wifiName5 = ssid_5g;
            this.dataForm.wifiPwd5 = key_5g;

        },

        // 点击下一步回调
        nextClick() {
            const fromArr = ['ruleForm2_4', 'ruleForm5', 'ruleForm_login'];
            if (this.formCheck(fromArr)) {
                let obj = {};

                const {to5G,  wifiName2_4, wifiPwd2_4, wifiName5, wifiPwd5,timeZoneValue} = this.dataForm;
            
                obj.to5G = to5G;
                obj.wifiName2_4 = wifiName2_4;
                obj.wifiPwd2_4 = wifiPwd2_4;

                // 设置5G，根据是否同步设置5G判断
                obj.wifiName5 = to5G ? wifiName2_4 : wifiName5;
                obj.wifiPwd5 = to5G ? wifiPwd2_4 : wifiPwd5;

                // 设置时区
                if (this.setTimeZone) {
                    obj.timeZoneValue = timeZoneValue;
                }
                console.log(obj);

                localStorage.setItem(LOCAL_KEY.IS_WIZARD_BASE_SETTING, JSON.stringify(obj));
                
                this.$router.replace(WIZARD_ROUTE.Completed);
                setWizardHistory(WIZARD_ROUTE.Completed);

                localStorage.removeItem(LOCAL_KEY.IS_SKIP_WIZARD);
            }
        },

        // 打开跳过确认弹窗
        openSkipDialog() {
            this.$refs.skipRef.show();
        },

        // 跳过
        async skipClick() {
            localStorage.removeItem(LOCAL_KEY.IS_WIZARD_BASE_SETTING);

            localStorage.setItem(LOCAL_KEY.IS_SKIP_WIZARD, true);

            this.$router.replace(WIZARD_ROUTE.Completed);

            setWizardHistory(WIZARD_ROUTE.Completed);
        },

        // 表单校验
        formCheck(formArr) {
            let status = [];

            formArr.forEach((r) => {
                if (this.$refs[r]) {
                    this.$refs[r].validate((valid) => {
                        status.push(valid);
                    });
                }
            });

            return !status.includes(false);
        },

        // 获取时区
        async fetchTimeZone() {
            const {timeZone} = await getNtpTime();
            this.dataForm.timeZoneValue = timeZone;
        },

        // 是否显示跳过按钮
        isShowSkip() {
            this.showSkip = false;
        },
    },

    watch: {
        'windowSize.width': {
            handler: function (nVal) {
                console.log('windowSize.width', nVal);
            }
        },
        'dataForm.toLoginPwd': {
            handler: function (nVal) {
                if (nVal) {
                    this.dataForm.noPwd = false;
                    this.dataForm.loginPwd = '';
                }
            }
        },
        'dataForm.wifiName2_4': {
            handler: function (nVal) {
                if (nVal) {
                    this.wifiNameBytes = getByteLength(nVal);
                    this.wifiNameLength = this.wifiNameBytes >= 32 ? nVal.length : 32;
                } else {
                    this.wifiNameBytes = 0;
                }
            }
        },
        'dataForm.wifiName5': {
            handler: function (nVal) {
                if (nVal) {
                    this.wifiNameBytes_5G = getByteLength(nVal);
                    this.wifiNameLength_5G = this.wifiNameBytes_5G >= 32 ? nVal.length : 32;
                } else {
                    this.wifiNameBytes_5G = 0;
                }
            }
        }
    },

    computed: {
        setLabel() {
            return true;
        },
        setLabelWidth() {
            const langAndWidth = new Map();

            langAndWidth.set('it', '165px');
            langAndWidth.set('es', '220px');
            langAndWidth.set('de', '140px');
            langAndWidth.set('fr', '150px');

            const lang = window.localStorage.getItem(LOCAL_KEY.IS_CURRENT_LANGUAGE);

            return 'auto';
        },
        setWifiNameTips() {
            return true;
        },
        setTimeZone() {
            return true;
        }
    },
    async created() {
        // 是否显示跳过按钮
        this.isShowSkip();

        const localBaseData = localStorage.getItem(LOCAL_KEY.IS_WIZARD_BASE_SETTING);

        if (localBaseData) {
            this.dataForm = JSON.parse(localBaseData);
        } else if (this.showSkip) {
            this.fetchWiFiData();
        }
        if (this.dataForm.timeZoneValue == '') {
            this.fetchTimeZone();
        }
        this.labelPosition = 'left';
    }
};
</script>

<style lang="less" scoped>
@import '@/assets/css/theme_blue/component_round.less';
@import '@/assets/css/theme_blue/component_common.less';
.page-2 {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .page-2-container {
        margin: 0 auto;
        width: 60%;

        .timeZone {
            display: flex;
            justify-content: center;
            align-items: center;
            .timeZone-title {
                width: 155px;
            }

            .timeZone-select {
                flex: 1%;
            }
        }

        .section-1,
        .section-2 {
            margin-bottom: 40px;
        }

        .section-1 {
            .basic-settings-tips {
                margin-top: 25px;
                color: rgba(0, 0, 0, 0.8);
                font-weight: 400;
            }
        }

        .section-2 {
            .check-box {
                line-height: 30px;
            }

            .wifi-name-tips {
                margin-bottom: 15px;
            }
        }

        .btn-content {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100px;

            /deep/.el-button {
                width: 450px;
            }
        }

        .skip-content {
            display: flex;
            align-items: center;
            justify-content: center;
            padding-bottom: 15px;

            /deep/.el-link--inner {
                font-weight: bold;
                text-decoration: underline;
            }
        }

        .section-title {
            font-weight: bold;
            color: #000000;
            font-size: 1.2em;
        }

        .section-chid-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-weight: bold;
        }
    }

    @media (max-width: 1024px) {
        .page-2-container {
            width: 85%;
        }
    }
}

/deep/.el-input {
    max-width: 100% !important;
}

/deep/ .el-switch__core {
    width: 54px !important;
    height: 31px;
    border-radius: 15px;

    &::after {
        width: 27px;
        height: 27px;
    }
}

/deep/ .el-switch.is-checked {
    .el-switch__core::after {
        margin-left: -27px;
    }
}
/deep/.el-input__inner {
    background: none;
    border: 1px #e4e7ed solid;
    color: #666161;
    max-width: 100% !important;
}

/deep/.el-checkbox__label {
    display: inline-grid;
    max-width: 450px;
    white-space: pre-line;
    word-wrap: break-word;
    line-height: 20px;
}

/deep/ .el-input--suffix {
    .el-input__inner {
        padding-right: 54px;
    }
}

.setLabel {
    /deep/.el-form-item__label {
        line-height: 52px;
        font-size: 13px;
    }
}
</style>
